Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

256
Visualizações
How to return null instead of undefined when using arr.map(elem => dict[elem]) in typescript?

I wrote a simple function to replace values in an array according to a look-up dictionary object:

// typescript
function recode(arr: any[], dict: Record<string, string> ) {
    return arr.map(el => dict[el])
}

It works as expected. However, I want the function to return null when array values have no match in the look-up dictionary.

So right now if I do:

// array input
const myArr: string[] = ['eggplant', 'tomato', 'carrot', 'cabbage'];

// look-up dictionary
const myDictionary: Record<string, string> = {
    eggplant: 'purple',
    tomato: 'red',
    carrot: 'orange'
};

function recode(arr: any[], dict: Record<string, string> ) {
    return arr.map(el => dict[el])
}

// calling recode()
recode(myArr, myDictionary) 
// returns 
// ["purple", "red", "orange", undefined] 

But I want the output to be

// ["purple", "red", "orange", null] 

Is there a simple enough way to achieve this, considering that I'm using typescript (not sure it makes a difference)?

Typescript REPL

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

You can use the nullish coalescing operator (??) to resolve null in cases of undefined (and use a generic type parameter to infer the type of values from the dict parameter):

TS Playground

const myArr: string[] = ['eggplant', 'tomato', 'carrot', 'cabbage'];

const myDictionary: Record<string, string> = {
    eggplant: 'purple',
    tomato: 'red',
    carrot: 'orange'
};

function recode <T extends Record<string, any>>(
  arr: readonly string[],
  dict: T,
): (T[keyof T] | null)[] {
    return arr.map(el => dict[el] ?? null);
}

const result = recode(myArr, myDictionary); // (string | null)[]
console.log(result);
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda